﻿namespace Resharper.Abstractions.CodeDom.Statements.TryStatements
{
  using System;
  using JetBrains.Annotations;
  using JetBrains.ReSharper.Psi.CSharp.Tree;
  using Resharper.Abstractions.Actions;
  using Resharper.Abstractions.CodeDom.TreeNodes;

  /// <summary>Defines the <see cref="TryStatementExtensions"/> class.</summary>
  public static class TryStatementExtensions
  {
    #region Public Methods

    /// <summary>Gets the selected literal expression.</summary>
    /// <param name="context">The context.</param>
    /// <returns>Returns the selected literal expression.</returns>
    [CanBeNull]
    public static TryStatement GetSelectedTryStatement([NotNull] this ProviderContext context)
    {
      if (context == null)
      {
        throw new ArgumentNullException("context");
      }

      var result = context.InternalGetSelectedElement<ITryStatement>();

      return result != null ? new TryStatement(result) : null;
    }

    /// <summary>Gets the parent try statement.</summary>
    /// <param name="tryStatement">The try statement.</param>
    /// <returns>Returns the parent try statement.</returns>
    [CanBeNull]
    public static TryStatement GetContainingTryStatement([NotNull] this TryStatement tryStatement)
    {
      var result = tryStatement.InternalTryStatement.GetContainingNode<ITryStatement>();

      return result != null ? new TryStatement(result) : null;
    }

    /// <summary>Gets the containing try statement.</summary>
    /// <param name="expression">The expression.</param>
    /// <returns>Returns the containing try statement.</returns>
    [CanBeNull]
    public static TryStatement GetContainingTryStatement([NotNull] this TreeNode expression)
    {
      var result = expression.InternalTreeNode.GetContainingNode<ITryStatement>();

      return result != null ? new TryStatement(result) : null;
    }

    #endregion
  }
}